/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com.procesos;

import pe.com.unidades.Vehiculo;
import com.google.gson.Gson;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.commons.io.IOUtils;
import pe.com.ColaProcesamiento;

/**
 *
 * @author romulogalindo
 */
public class ProcesadorSunarp extends Proceso implements Runnable {

    Vehiculo vehiculo;

    public ProcesadorSunarp() {
        try {
            InputStream input = new URL("http://sd3.accesocrediticio.com:8070/wservices/SunarpServlet?placa=" + URLEncoder.encode("cgp757", "UTF-8")).openStream();
            pe.com.unidades.Sunarp map = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), pe.com.unidades.Sunarp.class);
            System.out.println("map:[" + map.getPlaca() + "],[" + map.getVim() + "],[" + map.getSerie() + "],[" + map.getPropietarios() + "]");
        } catch (Exception ep) {
            System.out.println("ep:" + ep.getMessage());
        }
    }

    public ProcesadorSunarp(Vehiculo sunarp) {
        this.vehiculo = sunarp;
    }

    @Override
    public void run() {
        try {
            System.out.println("http://sd3.accesocrediticio.com:8070/wservices/SunarpServlet?placa=" + URLEncoder.encode(vehiculo.getCo_plaveh(), "UTF-8"));
            InputStream input = new URL("http://sd3.accesocrediticio.com:8070/wservices/SunarpServlet?placa=" + URLEncoder.encode(vehiculo.getCo_plaveh(), "UTF-8")).openStream();
            pe.com.unidades.Sunarp sn = new Gson().fromJson(new InputStreamReader(input, "UTF-8"), pe.com.unidades.Sunarp.class);
            vehiculo.setNu_serveh(sn.getSerie());
            vehiculo.setNu_ideveh(sn.getVim());
            vehiculo.setNu_motveh(sn.getMotor());
            vehiculo.setNo_colveh(sn.getColor());
            vehiculo.setNo_marveh(sn.getMarca());
            vehiculo.setNo_modveh(sn.getModelo());
            String prop = "";
//            System.out.println("aqui:" + sn.getPropietarios().size());
            if (sn.getPropietarios().size() > 1) {
                for (String p : sn.getPropietarios()) {
                    prop = prop.replaceAll("\'", "\'\'") + p + ";";
                }
                prop = prop.substring(0, prop.length() - 1);
                vehiculo.setNo_proveh(prop);
            } else {
                prop = sn.getPropietarios().get(0).replaceAll("\'", "\'\'");
                vehiculo.setNo_proveh(prop);
            }
            vehiculo.setNo_sedveh(sn.getSede());
            ColaProcesamiento.nuevoProceso(vehiculo);
        } catch (Exception ep) {
            System.out.println("[Ferenata] run-> error:" + ep.getMessage());
            ep.printStackTrace();
        }
    }

}
